package com.cn.lotary.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Jason 16-Jul-2011
 */
public class ObjectUtil {

    public static Object getPropertyType(Class<?> cls, String propertyName) {
        Object retvalue = null;
        try {
            if (propertyName.contains(".")) {
                String[] type = propertyName.split("\\.");

                for (int i = 0; i < type.length - 1; i++) {
                    cls = cls.getDeclaredField(type[i]).getType();
                }

                propertyName = type[type.length - 1];
            }
            Field field = cls.getDeclaredField(propertyName);
            // field.setAccessible(true);
            retvalue = field.getType();
        } catch (Exception e) {
            LoggerUtils.error(e);
        }
        return retvalue;
    }

    public static boolean isInterger(Object o) {
        return o.equals(Integer.class);
    }

    public static boolean isString(Object o) {
        return o.equals(String.class);
    }

    public static boolean isLong(Object o) {
        return o.equals(Long.class);
    }

    public static boolean islong(Object o) {
        return o.equals(long.class);
    }

    public static boolean isDate(Object o) {
        return o.equals(Date.class);
    }

    public static boolean canConverterToInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 首 字 母 转 大 写
     *
     * @param str
     * @return String
     */
    public static String toUpperCase(String str) {
        String[] a = str.split("");
        return str.replaceFirst(a[1], a[1].toUpperCase());
    }

    /**
     * 首 字 母 转 小 写
     *
     * @param str
     * @return String
     */
    public static String toLowerCase(String str) {
        String[] a = str.split("");
        return str.replaceFirst(a[1], a[1].toLowerCase());
    }

    /**
     * 将表名转为实体名
     *
     * @param str table name
     * @return String entity name
     */
    public static String tableNameToEntityName(String str) {
        String[] split = str.split("_");
        StringBuilder entityName = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            entityName.append(toUpperCase(split[i]));
        }
        return entityName.toString();
    }

    /**
     * 将表列名转为实体属性名
     *
     * @param str table column name
     * @return String entity filed name
     */
    public static String columnNameToFieldName(String str) {
        String tableNameToEntityName = tableNameToEntityName(str);
        return toLowerCase(tableNameToEntityName);
    }

    public static String getEntityFildeNameByEntityMethodName(String methodName) {
        String fildeName = methodName.replace("get", "");
        return toLowerCase(fildeName);
    }

    public static String getGetMethodNameByFiledName(String filedName) {
        String methodName = "get" + toUpperCase(filedName);
        return methodName;
    }

    /**
     * 通过表列名得到实体方法名
     *
     * @param str table column name
     * @return entity field name
     */
    public static String columnNameToGetMethos(String str) {
        String tableNameToEntityName = tableNameToEntityName(str);
        return "get" + toUpperCase(tableNameToEntityName);
    }

    public static boolean eamilValidation(String email) {
        //TODO:try
        String p = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(p);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    /**
     * in testing
     *
     * @param <T>
     * @param a
     * @return
     */
    //TODO:分析可变参数
    public static <T> List<T> asList(T... a) {
        ArrayList<T> arrayList = new ArrayList<T>();
        arrayList.addAll(Arrays.asList(a));
        return arrayList;
    }

    /**
     * in testing
     *
     * @param <T>
     * @param a
     * @return
     */
    public static <T> List<T> removeDuplicate(List<T> a) {
        HashSet<T> hashSet = new HashSet<T>(a);
        a.clear();
        a.addAll(hashSet);
        return a;
    }

    public static boolean isNotEmpty(String str) {
        return (str != null && !"".equals(str) && str.length() > 0);
    }

    /**
     * JSF Download
     *
     * @param path file path
     */
    private void downloadFile(String path) {
        InputStream fis = null;
        try {
            File file = new File(path);
            fis = new FileInputStream(file);
            byte[] buf = new byte[fis.available()];
            int offset = 0;
            int numRead = 0;
            while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length - offset)) >= 0)) {
                offset += numRead;
            }
            fis.close();
            HttpServletResponse response =
                    (HttpServletResponse) FacesContext.getCurrentInstance()
                    .getExternalContext().getResponse();
            response.setContentType("application/zip");
            String name = path.substring(path.lastIndexOf("/") + 1);
            LoggerUtils.debug(name);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8") + "");
            response.getOutputStream().write(buf);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception ex) {
            LoggerUtils.error(ex);
        } finally {
            try {
                fis.close();
            } catch (Exception ex) {
                LoggerUtils.error(ex);
            }
        }
    }
}
